import authapi from './authapi.js'

const state = {
  payload: {},
  alias: {
    uid: 'uid',
    uname: 'username',
    truename: 'truename',
    jwt: 'jwt',
    jwtRef: 'jwt_refresh',
    acos: 'acos',
    group: 'group'
  },
  status: 'out'
}

// getters
const getters = {
  auth: (state) => (key) => {
    if (!state.alias[key]) {
      return null
    }
    if (state.payload && state.payload.hasOwnProperty(state.alias[key])) {
      return state.payload[state.alias[key]]
    } else {
      return null
    }
  }
}

// actions
const actions = {
  loginIn: function({ commit }, userinfo) {
    authapi.loginIn(userinfo)
    commit('setAuth', userinfo)
  },
  loginOut: function({ commit }) {
    authapi.loginOut()
    commit('setOut')
  },
  loginNeed: function({ commit }) {
    commit('setNeed')
  },
  getAuth: function({ commit }) {
    authapi.getAuth(
      (res) => commit('setAuth', res),
      () => commit('setOut')
    )
  },
  updateAuth: function({ commit, state }, vals) {
    const p = {}
    for (const k in vals) {
      p[state.alias[k]] = vals[k]
    }
    authapi.update(p)
    commit('updateAuth', p)
  }
}

// mutations
const mutations = {
  setAuth: function(state, res) {
    state.status = 'in'
    state.payload = res
  },
  setOut: function(state) {
    state.status = 'out'
    state.payload = {}
  },
  setNeed: function(state) {
    state.status = 'need'
    state.payload = {}
  },
  updateAuth: function(state, vals) {
    for (const k in vals) {
      state.payload[k] = vals[k]
    }
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
